<!--  -->
<template>
  <div>
    <el-tree
      :data="categorys"
      :props="defaultProps"
      show-checkbox
      node-key="catId"
      :default-expanded-keys="expandedKey"
      :expand-on-click-node="false"
      draggable
      @node-drop="handleDrop"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            添加</el-button
          >
          <el-button type="text" size="mini" @click="edit(data)">
            修改
          </el-button>
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
            >删除</el-button
          >
        </span>
      </span>
    </el-tree>

    <el-dialog
      :title="dialogMessage"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="categoryForm">
        <el-form-item label="分类名称">
          <el-input v-model="categoryForm.name"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="categoryForm.icon"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="categoryForm.productUnit"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogClose">取 消</el-button>
        <el-button type="primary" @click="submitCategory">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  components: {},
  computed: {},
  watch: {},
  data() {
    return {
      updateNodes: [],
      maxLength: 0,
      dialogMessage: "",
      // 0:add 1:edit
      dialogType: 0,
      categoryForm: {
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 0,
        sort: 0,
        catId: 0,
        icon: "",
        productUnit: "",
      },
      dialogVisible: false,
      categorys: [],
      expandedKey: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },

  methods: {
    getCategorys() {
      this.$http({
        url: this.$http.adornUrl("/product/category/tree"),
        method: "get",
      }).then(({ data }) => {
        this.categorys = data.data;
      });
    },

    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log(draggingNode, dropNode, dropType, ev);
      // 1. 拿到最新的父节点信息
      let pCid = 0;
      let brathor = null;
      // 兄弟，父亲的关系
      if (dropType == "before" || dropType == "after") {
        pCid = dropNode.parent.data.catId == undefined
            ? 0
            : dropNode.parent.data.catId;
        brathor = dropNode.parent.childNodes;
      } else if (dropType == "inner") {
        pCid = dropNode.data.catId;
        // 2.计算出当前的sort
        brathor = dropNode.childNodes;
      }

      for (let i = 0; i < brathor.length; i++) {
        // 如果遍历的是当前拖拽的节点
        if (brathor[i].data.catId == draggingNode.data.catId) {
          // 当前节点层级发生变化
          if (brathor[i].level != draggingNode.level) {
            this.updateChildNodeLevel(brathor[i]);
          }
          this.updateNodes.push({
            catId: brathor[i].data.catId,
            sort: i,
            parentCid: pCid,
          });
        } else {
          this.updateNodes.push({ catId: brathor[i].data.catId, sort: i });
        }
      }


     /* this.$http({
        url: this.$http.adornUrl("/product/category/batchUpdate"),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false),
      }).then(({ data }) => {
        this.getCategorys();
        this.expandedKey = [draggingNode.data.catId];
        this.updateNodes = [];
        if (data && data.code === 0) {
          this.$message({
            message: "操作成功",
            type: "success",
            duration: 1500,
          });
        } else {
          this.$message.error(data.msg);
        }
      }); */
    },

    updateChildNodeLevel(node) {
      if (node.childNodes.length > 0) {
        for (let index = 0; index < node.childNodes.length; index++) {
          var cNode = node.childNodes[i].data;
          this.updateNodes.push({
            catId: cNode.catId,
            catLevel: node.childNodes[i].level,
          });
          this.updateChildNodeLevel(node.childNodes[i]);
        }
      }
    },

    allowDrop(draggingNode, dropNode, type) {
      // 1.被拖动的层数与目标父节点总层数不能大于3
      this.currentNodeLevel(draggingNode.data);
      let deep = this.maxLength - draggingNode.data.catLevel + 1;
      if (type == "inner") {
        return deep + dropNode.level <= 3;
      }
      return deep + dropNode.parent.level <= 3;
    },

    currentNodeLevel(node) {
      if (node.children != null && node.children.length > 0) {
        for (let i = 0; i < node.children.length; i++) {
          if (node.children[i].catLevel > this.maxLength) {
            this.maxLength = node.children[i].catLevel;
          }
          this.currentNodeLevel(node.children[i]);
        }
      }
    },

    addCategory() {
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.categoryForm, false),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dialogVisible = false;
          this.expandedKey = [this.categoryForm.parentCid];
          this.$message({
            message: "操作成功",
            type: "success",
            duration: 1500,
            onClose: () => {
              this.getCategorys();
            },
          });
        } else {
          this.$message.error(data.msg);
        }
      });
    },

    editCategory() {
      var { catId, name, icon, productUnit } = this.categoryForm;
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData({ catId, name, icon, productUnit }, false),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dialogVisible = false;
          this.expandedKey = [this.categoryForm.parentCid];
          this.$message({
            message: "操作成功",
            type: "success",
            duration: 1500,
            onClose: () => {
              this.getCategorys();
            },
          });
        } else {
          this.$message.error(data.msg);
        }
      });
    },

    dialogClose() {
      (this.categoryForm = {
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 0,
        sort: 0,
        catId: 0,
      }),
        (this.dialogVisible = false);
    },

    submitCategory() {
      if (this.dialogType == 0) {
        this.addCategory();
      } else if (this.dialogType == 1) {
        this.editCategory();
      } else {
        alert("error.");
      }
    },

    edit(data) {
      this.dialogMessage = "修改数据";
      this.dialogType = 1;
      this.dialogVisible = true;

      // 从数据库中查询
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "post",
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.categoryForm.name = data.category.name;
          this.categoryForm.catId = data.category.catId;
          this.categoryForm.icon = data.category.icon;
          this.categoryForm.productUnit = data.category.productUnit;
          this.categoryForm.parentCid = data.category.parentCid;
          this.categoryForm.catLevel = data.category.catLevel;
          this.categoryForm.showStatus = data.category.showStatus;
          this.categoryForm.sort = data.category.sort;
          this.categoryForm.showStatus = data.category.showStatus;
        } else {
          this.$message.error(data.msg);
        }
      });
    },

    append(data) {
      this.dialogMessage = "新增数据";
      this.dialogType = 0;
      this.dialogVisible = true;

      this.categoryForm.parentCid = data.catId;
      this.categoryForm.catLevel = data.catLevel * 1 + 1;
      this.categoryForm.name = "";
      this.categoryForm.catId = null;
      this.categoryForm.icon = "";
      this.categoryForm.productUnit = "";
      this.categoryForm.showStatus = 0;
      this.categoryForm.sort = 0;
    },

    remove(node, data) {
      var ids = [data.catId];
      var names = [data.name];
      this.$confirm(
        `确定对[${names.join(",")}]进行[${ids ? "删除" : "批量删除"}]操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getCategorys();
                  this.expandedKey = [node.parent.data.catId];
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
  },
  created() {
    this.getCategorys();
  },
};
</script>
<style scoped>
</style>